package Java7_Concurrency_Cookbook.thread_executor_framework.future_task_done;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * executor 执行 FutureTask 类型的任务, 当任务结束时, FutureTask 会调用 done() 方法
 * @author lixiangke
 * @date 2017/11/20
 */
public class Main {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        ExecutorService executor = Executors.newCachedThreadPool();
        ResultTask[] resultTasks = new ResultTask[5];
        for (int i = 0; i < 5; i++) {
            ExecutableTask executableTask = new ExecutableTask("Zoom" + i);
            resultTasks[i] = new ResultTask(executableTask);
            executor.submit(resultTasks[i]);
        }

        try {
            TimeUnit.SECONDS.sleep(5);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        for (int i = 0; i < resultTasks.length; i++) {
            resultTasks[i].cancel(true);
        }

        for (int i = 0; i < resultTasks.length; i++) {
            if (!resultTasks[i].isCancelled()) {
                System.out.printf("%s\n", resultTasks[i].get());
            }
        }

        executor.shutdown();
    }
}
